import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
const dd = {}
      dd.isString = (val)=>{
        return val !== null && typeof val === 'string'
      }
      dd.isObject = (val)=>{
        return val !== null && typeof val === 'object'
      }
const mapStore = (mName,mapData,type)=>{
    if(!mapData){
      return {}
    }
    let methodsMap = {
      state:mapState,
      getter:mapGetters,
      mutation:mapMutations,
      action:mapActions
    }
    if(Array.isArray(mapData)){
      return mName ? methodsMap[type](mName,mapData) : methodsMap[type](mapData)
    }else if(dd.isObject(mapData)) {
      let ret = {}
      for(let key of Object.keys(mapData)){
          if(key === 'global' || !mName){
            ret = {
              ...ret,
              ...methodsMap[type](mapData[key])
            }
          }else {
            ret = {
              ...ret,
              ...methodsMap[type](mName,mapData[key])
            }
          }

      }
      return ret
    }
}



dd.component = (obj,fildMap,state)=>{
  obj = obj || {}
  const options = {
    ...obj
  }
  if(state){
    let { beforeCreate, destroyed } = obj
    let {mName,store} = state
    options.beforeCreate = function () {
      this.$store.registerModule(mName, store)
    }
    options.updated = function(){
      this.$store.registerModule(mName, store)
      //location.reload()
    }
    options.destroyed = function () {
      this.$store.unregisterModule(mName)
    }
    if(fildMap){
      options.methods = {
        ...mapStore(mName,fildMap.mutations,'mutation'),
        ...mapStore(mName,fildMap.actions,'action'),
        ...obj.methods
      }
      options.computed = {
        ...mapStore(mName,fildMap.state,'state'),
        ...mapStore(mName,fildMap.getters,'getter'),
        ...obj.computed
      }
    }
  }else {
    if(fildMap){
      options.methods = {
        ...mapStore(null,fildMap.mutations,'mutation'),
        ...mapStore(null,fildMap.actions,'action'),
        ...obj.methods
      }
      options.computed = {
        ...mapStore(null,fildMap.state,'state'),
        ...mapStore(null,fildMap.getters,'getter'),
        ...obj.computed
      }
    }
  }

  obj = null
  return options
}
export default dd
